package org.myblog.myblogserver.code.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.myblog.myblogserver.code.entity.Admin;
import org.myblog.myblogserver.code.entity.User;
import org.myblog.myblogserver.code.mapper.AdminMapper;
import org.myblog.myblogserver.code.service.AdminService;
import org.myblog.myblogserver.config.GlobalConfig;
import org.myblog.myblogserver.config.properties.JwtProperties;
import org.myblog.myblogserver.dao.UserLoginDao;
import org.myblog.myblogserver.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper,Admin> implements AdminService {
    @Autowired
    private JwtProperties jwtProperties;
    public UserLoginDao login(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("password", password);
        Admin admin = getOne(queryWrapper);
        if (admin == null) {
            return null;
        }
        UserLoginDao userLoginDao=generateJwt(admin);
        return userLoginDao;
    }

    public Boolean sign(Admin admin) {
        admin.setId(null);
        if (!save(admin)) {
            return false;
        }
        return true;
    }

    protected UserLoginDao generateJwt(Admin userInfo) {
        //权限验证成功，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();

        claims.put("wushang", userInfo.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginDao userLoginDao = UserLoginDao.builder()
                .id(String.valueOf(userInfo.getId()))
                .userName(userInfo.getUsername())
                .token(token)
                .build();
        return userLoginDao;
    }
}